using System;
using System.Collections;
using System.Collections.Generic;
using Rilisoft.MiniJson;
using UnityEngine;
using UnityEngine.SceneManagement;

public class StarterPacksManager : MonoBehaviour
{
	public static StarterPacksManager instance;

	private string platfirmSpecificFolder = "ios/";

	public List<StarterPack> availableStarterPacks;

	private Dictionary<string, Dictionary<GamerType, string>> starterPacksHeader = new Dictionary<string, Dictionary<GamerType, string>>();

	public bool starterPacksHeaderLoaded;

	public bool starterPacksEnabled = true;

	public List<TierStarterPackEvent> tierStarterPackEvents;

	public List<DeathsCountStarterPackEvent> deathsCountStarterPackEvent;

	public List<RoundCountStarterPackEvent> roundCountStarterPackEvents;

	private int loseCount;

	public string endTutorEvent;

	public string travelOnFoot;

	public int timeToUnlockunlockLastEvent;

	public int loseCountToUnlockunlockLastEvent;

	private int lastCupsCount
	{
		get
		{
			return BCWStorage.Get<int>("SP_LastCapsCount");
		}
		set
		{
			BCWStorage.Set("SP_LastCapsCount", value, true);
		}
	}

	private int lastDeathsCount
	{
		get
		{
			return BCWStorage.Get<int>("SP_LastDeathsCount");
		}
		set
		{
			BCWStorage.Set("SP_LastDeathsCount", value, true);
		}
	}

	private string lastProcessedProgressEvent
	{
		get
		{
			return BCWStorage.Get<string>("SP_LastProcessedProgressEvent");
		}
		set
		{
			BCWStorage.Set("SP_LastProcessedProgressEvent", value, true);
		}
	}

	public bool giveTravelOnFootPack
	{
		get
		{
			return BCWStorage.Get<bool>("SP_GiveTravelOnFootPack");
		}
		set
		{
			BCWStorage.Set("SP_GiveTravelOnFootPack", value, true);
		}
	}

	public event Action onAvailableStarterPacksUpdated;

	private void Awake()
	{
		instance = this;
		UnityEngine.Object.DontDestroyOnLoad(this);
		if (Application.platform == RuntimePlatform.OSXEditor)
		{
			platfirmSpecificFolder = "ios/";
		}
		else if (Application.platform == RuntimePlatform.IPhonePlayer)
		{
			platfirmSpecificFolder = "ios/";
		}
		else if (Application.platform == RuntimePlatform.Android)
		{
			platfirmSpecificFolder = "android/";
		}
	}

	private void Start()
	{
		JSONManager.Instance.serverTimeUpdate += Init;
	}

	private void OnDestroy()
	{
		JSONManager.Instance.serverTimeUpdate -= Init;
	}

	public void Init()
	{
		BCWDebug.LogError("Init Wait");
		if (IOSInternetConnection.isEnable || FirstLoading.loadSkinScene)
		{
			StartCoroutine(WaitLoadInfoForNormalPlayer());
			return;
		}
		BCWDebug.LogError("Init not Wait");
		if (!starterPacksHeaderLoaded)
		{
			DownloadStarterPacksHeader();
			DownloadAllAvailableStarterPacks();
		}
	}

	private IEnumerator WaitLoadInfoForNormalPlayer()
	{
		while (IOSInternetConnection.isEnable || FirstLoading.loadSkinScene)
		{
			yield return null;
		}
		Init();
		yield return null;
	}

	private List<string> GetAvailableStarterPackIDs()
	{
		return new List<string>(BCWStorage.Get<string>("AvailableStarterPackIDs").Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries));
	}

	public void AddAvailableStarterPackID(string starterPackID)
	{
		List<string> availableStarterPackIDs = GetAvailableStarterPackIDs();
		if (!availableStarterPackIDs.Contains(starterPackID))
		{
			availableStarterPackIDs.Add(starterPackID);
			BCWStorage.Set("AvailableStarterPackIDs", string.Join("|", availableStarterPackIDs.ToArray()), true);
		}
	}

	public void RemoveAvailableStarterPackID(string starterPackID)
	{
		List<string> availableStarterPackIDs = GetAvailableStarterPackIDs();
		if (availableStarterPackIDs.Contains(starterPackID))
		{
			availableStarterPackIDs.Remove(starterPackID);
			BCWStorage.Set("AvailableStarterPackIDs", string.Join("|", availableStarterPackIDs.ToArray()), true);
		}
	}

	private List<string> GetUnprocessedEvents()
	{
		return new List<string>(BCWStorage.Get<string>("UnprocessedStarterPackEvents").Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries));
	}

	public void AddUnprocessedEvent(string starterPackID)
	{
		List<string> unprocessedEvents = GetUnprocessedEvents();
		if (!unprocessedEvents.Contains(starterPackID))
		{
			unprocessedEvents.Add(starterPackID);
			BCWStorage.Set("UnprocessedStarterPackEvents", string.Join("|", unprocessedEvents.ToArray()), true);
		}
	}

	public void RemoveUnprocessedEvent(string starterPackID)
	{
		List<string> unprocessedEvents = GetUnprocessedEvents();
		if (unprocessedEvents.Contains(starterPackID))
		{
			unprocessedEvents.Remove(starterPackID);
			BCWStorage.Set("UnprocessedStarterPackEvents", string.Join("|", unprocessedEvents.ToArray()), true);
		}
	}

	private void DealWithUnprocessedEvents()
	{
		foreach (string unprocessedEvent in GetUnprocessedEvents())
		{
			UnlockStarterPack(unprocessedEvent);
		}
	}

	private void DownloadAllAvailableStarterPacks()
	{
		foreach (string availableStarterPackID in GetAvailableStarterPackIDs())
		{
			if (!string.IsNullOrEmpty(availableStarterPackID))
			{
				DownloadAvailableStarterPack(availableStarterPackID);
			}
		}
	}

	private void DownloadAvailableStarterPack(string starterPackID)
	{
		BCWDebug.LogError("***************************** Available Starter Pack Download: " + starterPackID);
		JsonDownloader.StartDownload("https://secure.pixelgunserver.com/bcw-config/starter_packs/" + platfirmSpecificFolder + starterPackID + ".json", null, ParseAvailableStarterPackJson);
	}

	private void ParseAvailableStarterPackJson(string starterPackJson)
	{
		StarterPack starterPack = JsonUtility.FromJson<StarterPack>(starterPackJson);
		if (starterPack != null && !availableStarterPacks.Contains(starterPack))
		{
			if (MergeStarterPack(starterPack))
			{
				starterPack.Init();
				if (JSONManager.Instance.ServerTimeLoad() && !starterPack.availableForPurcase)
				{
					RemoveAvailableStarterPackID(starterPack.ID);
					availableStarterPacks.Remove(starterPack);
				}
			}
			if (this.onAvailableStarterPacksUpdated != null)
			{
				this.onAvailableStarterPacksUpdated();
			}
		}
		else if (starterPack != null)
		{
			BCWDebug.LogError("Parse available starter pack Error!");
		}
	}

	private void DownloadNewStarterPack(string starterPackID)
	{
		BCWDebug.LogError("***************************** New Starter Pack Download: " + starterPackID);
		JsonDownloader.StartDownload("https://secure.pixelgunserver.com/bcw-config/starter_packs/" + platfirmSpecificFolder + starterPackID + ".json", null, ParseNewStarterPackJson);
	}

	private void ParseNewStarterPackJson(string starterPackJson)
	{
		StarterPack starterPack = JsonUtility.FromJson<StarterPack>(starterPackJson);
		if (starterPack != null && !availableStarterPacks.Contains(starterPack))
		{
			starterPack.Init();
			if (MergeStarterPack(starterPack))
			{
				if (starterPack.groupID == "progress")
				{
					lastProcessedProgressEvent = starterPack.eventID;
				}
				if (starterPack.SetAvailable())
				{
					MainStarterPacksUI.instance.ShowStarterPackUI(starterPack);
				}
			}
			if (this.onAvailableStarterPacksUpdated != null)
			{
				this.onAvailableStarterPacksUpdated();
			}
		}
		else if (starterPack == null)
		{
			BCWDebug.LogError("Parse new starter pack Error!");
		}
	}

	private bool MergeStarterPack(StarterPack starterPack)
	{
		RemoveUnprocessedEvent(starterPack.eventID);
		StarterPack starterPack2 = availableStarterPacks.Find((StarterPack x) => x.groupID == starterPack.groupID);
		if (starterPack2 == null)
		{
			AddAvailableStarterPackID(starterPack.ID);
			availableStarterPacks.Add(starterPack);
			return true;
		}
		if (starterPack2.weight < starterPack.weight)
		{
			availableStarterPacks.Remove(starterPack2);
			RemoveAvailableStarterPackID(starterPack2.ID);
			AddAvailableStarterPackID(starterPack.ID);
			availableStarterPacks.Add(starterPack);
			return true;
		}
		return false;
	}

	private void DownloadStarterPacksHeader()
	{
		JsonDownloader.StartDownload("https://secure.pixelgunserver.com/bcw-config/starter_packs/starter_packs_header_new.json", null, ParseStarterPacksHeaderJson);
	}

	private void ParseStarterPacksHeaderJson(string starterPacksHeaderJson)
	{
		Dictionary<string, object> dictionary = Json.Deserialize(starterPacksHeaderJson) as Dictionary<string, object>;
		starterPacksEnabled = Convert.ToInt32(dictionary["Enabled"]) == 1;
		starterPacksHeader.Clear();
		foreach (KeyValuePair<string, object> item in dictionary["Events"] as Dictionary<string, object>)
		{
			Dictionary<string, object> dictionary2 = item.Value as Dictionary<string, object>;
			Dictionary<GamerType, string> dictionary3 = new Dictionary<GamerType, string>();
			foreach (KeyValuePair<string, object> item2 in dictionary2)
			{
				int result;
				if (int.TryParse(item2.Key, out result))
				{
					dictionary3.Add((GamerType)result, item2.Value.ToString());
				}
			}
			starterPacksHeader.Add(item.Key, dictionary3);
		}
		if (!string.IsNullOrEmpty(starterPacksHeaderJson))
		{
			DealWithUnprocessedEvents();
			if (JSONManager.Instance.lastTimeInGameOnline > 0 && JSONManager.Instance.GetServerTime() - JSONManager.Instance.lastTimeInGameOnline >= timeToUnlockunlockLastEvent)
			{
				CoroutineRunner.Invoke(3f, UnlockLastProcessedProgressEvent);
			}
			starterPacksHeaderLoaded = true;
		}
	}

	private void PrintStarterPacksHeader()
	{
		BCWDebug.LogError("***************** PrintStarterPacksHeader *****************");
		foreach (KeyValuePair<string, Dictionary<GamerType, string>> item in starterPacksHeader)
		{
			BCWDebug.LogError("Event: " + item.Key);
			foreach (KeyValuePair<GamerType, string> item2 in item.Value)
			{
				BCWDebug.LogError("\tGamerType: " + item2.Key);
				BCWDebug.LogError("\t\tStarterPack: " + item2.Value);
			}
		}
		BCWDebug.LogError("***********************************************************");
	}

	public void UnlockStarterPack(string eventName)
	{
		BCWDebug.Log("***************************** UnlockStarterPack: " + eventName);
		AddUnprocessedEvent(eventName);
		if (!starterPacksEnabled)
		{
			return;
		}
		string starterPackByEvent = GetStarterPackByEvent(eventName);
		if (!string.IsNullOrEmpty(starterPackByEvent))
		{
			if (GetAvailableStarterPackIDs().Contains(starterPackByEvent))
			{
				RemoveUnprocessedEvent(eventName);
			}
			else
			{
				DownloadNewStarterPack(starterPackByEvent);
			}
		}
	}

	private string GetStarterPackByEvent(string eventName)
	{
		if (starterPacksHeader.ContainsKey(eventName) && starterPacksHeader[eventName].ContainsKey(InAppShop.currentGamerType))
		{
			return starterPacksHeader[eventName][InAppShop.currentGamerType];
		}
		BCWDebug.LogError("Starter packs header doesn't contains needed starter pack! \n Event name: " + eventName + "\n Current gamer type: " + InAppShop.currentGamerType);
		return null;
	}

	public bool TryPurchaseStarterPackIAP(StarterPack starterPack)
	{
		BCWDebug.LogError("**********************  Try Purchase Starter Pack IAP **********************");
		BCWDebug.LogError("starterPack.ID: " + starterPack.ID);
		BCWDebug.LogError("starterPack.aipID: " + starterPack.iapID);
		BCWStorage.Set("PurchaseStarterPackIAP", starterPack.ID, true);
		InAppShop.instance.BuyIap(starterPack.iapID);
		return true;
	}

	public void SucessfulPurchaseStarterPackIAP(string iapID)
	{
		BCWDebug.LogError("********************** Sucessful Purchase Starter Pack IAP **********************");
		BCWDebug.LogError("aipID: " + iapID);
		string purchasedStarterPackID = BCWStorage.Get<string>("PurchaseStarterPackIAP");
		if (string.IsNullOrEmpty(purchasedStarterPackID))
		{
			BCWDebug.LogError("Starter pack purchasind wasn't started propprly!");
			return;
		}
		StarterPack starterPack = availableStarterPacks.Find((StarterPack x) => x.ID == purchasedStarterPackID);
		if (starterPack != null)
		{
			starterPack.GiveRewards();
			RemoveAvailableStarterPackID(starterPack.ID);
			BCWStorage.Set("PurchaseStarterPackIAP", string.Empty, true);
		}
		else
		{
			BCWDebug.LogError("Available starter pack list doesn't contains needed starter pack!  purchasedStarterPackID: " + purchasedStarterPackID);
		}
		MainStarterPacksUI.instance.HideStarterPackUI();
		if (this.onAvailableStarterPacksUpdated != null)
		{
			this.onAvailableStarterPacksUpdated();
		}
	}

	public void UnsecessfulPurchaseStarterPackIAP(string iapID)
	{
		MainStarterPacksUI.instance.starterPackUI.blockScreen.SetActive(false);
		BCWStorage.Set("PurchaseStarterPackIAP", string.Empty, true);
	}

	private void OnLevelWasLoaded(int level)
	{
		if (!(SceneManager.GetActiveScene().name == "Lobby"))
		{
			return;
		}
		CoroutineRunner.Invoke(3f, delegate
		{
			TierEvents();
			DeathsCountEvents();
			if (giveTravelOnFootPack)
			{
				giveTravelOnFootPack = false;
				UnlockStarterPack(travelOnFoot);
			}
		});
	}

	public void TierEvents()
	{
		int cups = CupsManager.Cups;
		foreach (TierStarterPackEvent tierStarterPackEvent in tierStarterPackEvents)
		{
			if (lastCupsCount < tierStarterPackEvent.cupsForEvent && cups >= tierStarterPackEvent.cupsForEvent)
			{
				UnlockStarterPack(tierStarterPackEvent.eventName);
			}
		}
		lastCupsCount = cups;
	}

	public void DeathsCountEvents()
	{
		int num = BCWStorage.Get<int>("PlayerDeaths");
		BCWDebug.LogError(" ********************** newDeathsCount = " + num + " lastDeathsCount = " + lastDeathsCount);
		foreach (DeathsCountStarterPackEvent item in deathsCountStarterPackEvent)
		{
			if (lastDeathsCount < item.deathsCount && num >= item.deathsCount)
			{
				UnlockStarterPack(item.eventName);
			}
		}
		lastDeathsCount = num;
	}

	public void RoundCountEvents(TypeGame typeGame, int roundsCount)
	{
		BCWDebug.LogError(" ********************** Rounds count key = " + settings.GetRoundCountKeyForGameMode(typeGame) + " Rounds count = " + roundsCount);
		foreach (RoundCountStarterPackEvent roundCountStarterPackEvent in roundCountStarterPackEvents)
		{
			switch (roundCountStarterPackEvent.typeGame)
			{
			case TypeGame.race:
			case TypeGame.RocketLeague:
				if ((typeGame == TypeGame.race || typeGame == TypeGame.RocketLeague) && roundCountStarterPackEvent.roundsCount == roundsCount)
				{
					UnlockStarterPack(roundCountStarterPackEvent.eventName);
				}
				break;
			case TypeGame.WalkingRobots:
			case TypeGame.TitanfallV2:
				if ((typeGame == TypeGame.TitanfallV2 || typeGame == TypeGame.WalkingRobots) && roundCountStarterPackEvent.roundsCount == roundsCount)
				{
					UnlockStarterPack(roundCountStarterPackEvent.eventName);
				}
				break;
			default:
				if (roundCountStarterPackEvent.typeGame == typeGame && roundCountStarterPackEvent.roundsCount == roundsCount)
				{
					UnlockStarterPack(roundCountStarterPackEvent.eventName);
				}
				break;
			}
		}
	}

	public void UnlockLastProcessedProgressEvent()
	{
		Debug.LogError("*********************************  UnlockLastProcessedProgressEvent *********************************");
		UnlockStarterPack(lastProcessedProgressEvent);
	}

	public void LoseCountEvent(TDMResult result)
	{
		switch (result)
		{
		case TDMResult.Loser:
			loseCount++;
			break;
		case TDMResult.Winner:
			loseCount = 0;
			break;
		}
		if (loseCount >= loseCountToUnlockunlockLastEvent)
		{
			UnlockLastProcessedProgressEvent();
			loseCount = 0;
		}
	}
}
